package org.system.core.controller.system;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.system.core.common.Result;
import org.system.core.domain.entity.SysConfig;
import org.system.core.domain.entity.SysMenu;
import org.system.core.domain.entity.SysUser;
import org.system.core.domain.model.RegisterBody;
import org.system.core.domain.vo.LoginBody;
import org.system.core.domain.vo.RouterVo;
import org.system.core.service.system.*;
import org.system.core.utils.SecurityUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author baoRoot
 */
@RestController
@RequestMapping("/auth")
@Api(tags={"登录模块"})
public class SysLoginController {

    private static final Logger logger = LoggerFactory.getLogger(SysLoginController.class);

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private SysConfigService sysConfigService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginBody loginBody) {
        logger.info("用户登录： {}", loginBody);
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        return Result.ok(token);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getInfo")
    public Result<Map<String, Object>> getInfo() {
        Map<String, Object> map = new HashMap<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Set<String> role = permissionService.getRolePermission(user);
        Set<String> permissions = permissionService.getMenuPermission(user);
        SysConfig sysConfig = sysConfigService.selectConfigByUserId(user.getUserId());
        logger.info("{} 获取用户信息", user.getUserName());
        user.setPassword("");
        map.put("user", user);
        map.put("role", role);
        map.put("permissions", permissions);
        map.put("config", sysConfig);
        return Result.ok(map);
    }

    @ApiOperation("获取菜单")
    @GetMapping("/getMenus")
    public Result<List<RouterVo>> getMenus() {
        Long userId = SecurityUtils.getUserId();
        logger.info("用户：{} 获取菜单", SecurityUtils.getUsername());
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return Result.ok(menuService.buildMenus(menus));
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterBody user) {
        logger.info("用户注册: {}", user);
        registerService.register(user);
        return Result.ok();
    }

}
